#include "StdAfx.h"
#include "TTTUDPSocket.h"


TTTUDPSocket::TTTUDPSocket()
{

}


TTTUDPSocket::~TTTUDPSocket(void)
{
}

BOOL TTTUDPSocket::InitSocket(LPCTSTR pszRemoteAddress, USHORT usPort, BOOL bSrv)
{
	m_Socket = WSASocket(AF_INET, SOCK_DGRAM, 0, NULL, 0, 0);
	if(INVALID_SOCKET == m_Socket) return FALSE;
	
	m_Sockaddr.sin_family = AF_INET;
	m_Sockaddr.sin_port = htons(usPort);
	if(bSrv) 
	{
		m_Sockaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
		bind(m_Socket, (const sockaddr*)&m_Sockaddr, sizeof(SOCKADDR));
	}
	else
	{
		m_Sockaddr.sin_addr.s_addr	= inet_addr("127.0.0.1");//inet_addr(CT2A(pszRemoteAddress));
	}
}

BOOL TTTUDPSocket::SendData(BYTE *pData, DWORD dwLen)
{
	DWORD dwSend;
	WSABUF wsaBuf;
	//wsaBuf.buf = (CHAR *)pData;
	//wsaBuf.len = dwLen;

	CString content=_T("Test");
	wsaBuf.buf = (CHAR*)content.GetBuffer(content.GetLength());
	wsaBuf.len = content.GetLength();

	if(SOCKET_ERROR == WSASendTo(m_Socket, &wsaBuf, 1, &dwSend, 0,
		(SOCKADDR*)&m_Sockaddr, sizeof(SOCKADDR), NULL, NULL))
	{
		return FALSE;
	}
	return dwSend != 0;
}

BOOL TTTUDPSocket::SendTo(LPCTSTR pszRemoteAddress, USHORT usPortt, BYTE *pData, DWORD dwLen)
{
	SOCKADDR_IN sockAddr;
	sockAddr.sin_family = AF_INET;
	sockAddr.sin_port = htons(usPortt);
	sockAddr.sin_addr.s_addr	= inet_addr(CT2A(pszRemoteAddress));
	DWORD dwSend;
	WSABUF wsaBuf;
	wsaBuf.buf = (CHAR *)pData;
	wsaBuf.len = dwLen;
	if(SOCKET_ERROR == WSASendTo(m_Socket, &wsaBuf, dwLen, &dwSend, 0,
		(SOCKADDR*)&sockAddr, sizeof(SOCKADDR), NULL, NULL))
	{
		return FALSE;
	}
	return dwSend != 0;
}

DWORD TTTUDPSocket::RecvData(BYTE *pData, DWORD dwMaxLen)
{
	WSABUF wsaBuf;
	wsaBuf.buf = (CHAR *)pData;
	wsaBuf.len = dwMaxLen;
	DWORD dwRead = 0;
	DWORD dwFlag = 0;
	SOCKADDR_IN addrFrom;
	INT iLen = sizeof(addrFrom);
	if(SOCKET_ERROR == WSARecvFrom(m_Socket, &wsaBuf, 1, &dwRead, &dwFlag,
		(SOCKADDR *)&addrFrom, &iLen, NULL, NULL))
	{
		dwRead = GetLastError();
		return 0;
	}
	return iLen;
}


